# -*- coding: utf-8  -*-
#    Patrolling Bot - A Python bot that uses Pywikipediabot framework and works on MediaWiki wikis at general.
#    Copyright (C) 2008 OsamaK
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#    Please report bugs or help imporving this program by connecting to <OsamaK.WFM@gmail.com>
import wikipedia
import time
from datetime import datetime
from datetime import timedelta
from okbot import *

site = wikipedia.getSite(code='en',fam='wikipedia')

def main():
  timenum = 0
  while True:
    if timenum == 0:
      rcstart = stats()
    else:
      rcstart = stats(rcstart)
    timenum = 1
    wikipedia.output("Sleep for 30 seconds.")
    time.sleep(30) # Can be changed freely.

def stats(rcstart='1'):
    #api.php?action=query&list=recentchanges&rcdir=newer&rctype=new&rcnamespace=1|7&rcshow=!redirect|!bot|!patrolled&rcprop=user|ids|title|timestamp&format=jsonfm
  predata = {
             'action': 'query',
             'meta': 'siteinfo',
             'list': 'recentchanges',
             'rcdir': 'newer',
             'rctype': 'new',
             'rcnamespace': '1|7', # Talk and Image talk only
             'rcshow': '!redirect|!bot|!patrolled', #you can add !anon if you're planning to ignore their edits
             'rcprop': 'user|ids|title|timestamp',
             'rclimit': '50',
             'rcstart': rcstart,
             'format': 'json',
              }
  data = getAPI(site, predata)

  if data == None: return rcstart # Was there any error?
  userList = getPatrolled()

  dateformat ="%Y-%m-%dT%H:%M:%SZ" # MediaWiki's format template
  try:
    if len(data['query']['recentchanges']) == 0:
      wikipedia.output("No items there!")
      return rcstart
  except: return rcstart

  for page in data['query']['recentchanges']:
    rcid = page['rcid']
    title = page['title']
    lastrcstart = page['timestamp']
    user = page['user'] # اسم المستخدم، يتم تمريره إلى دالة "هل مستخدم" للتأكد من كون المستخدم في القائمة البيضاء

    # Well, What are you doing there?! OK, We convert MediaWiki's format to Python one and add a second, then return it back in MediaWiki's format.
    locals()['strpdate'] = time.strptime(lastrcstart, locals()["dateformat"]) # Convert MediaWiki's format to a tuple.
    globals()['plussec'] = datetime(locals()["strpdate"][0],locals()["strpdate"][1],locals()["strpdate"][2],locals()["strpdate"][3],locals()["strpdate"][4],locals()["strpdate"][5],locals()["strpdate"][6]) + timedelta(seconds=1) # Adding the tuple as Python format and plus a second.

    talkpage = wikipedia.Page(site, title)
    if user in userList:
      token = talkpage.site().getToken(talkpage)
      wikipedia.output("Patrolling %s, Created by %s" % (title, user))
      predata = {
                'action': 'patrol',
                'token': token,
                'rcid': str(rcid),
                'format': 'json',
                }
      getAPI(site, predata)
      wikipedia.output("Sleep for 10 seconds.")
      time.sleep(10)

  return plussec.strftime(dateformat)

def getPatrolled():
  ignoredusers = []
  ignoredpage = wikipedia.Page(site,u"User:OsamaK/Patrolled.js")

  try:
    for line in ignoredpage.get().split('\n'):
      if line.startswith(u"* [[User:") and line.endswith(u"]]"):
        ignoredusers.append(line.lstrip(u"* [[User:").rstrip(u"]]"))
  except wikipedia.NoPage:
    wikipedia.output("No ignored users page, skipped")
    return ignoredusers

  printignored = "White list is: "
  for user in ignoredusers:
    printignored = printignored + user + " "

  print printignored

  return ignoredusers

if __name__ == '__main__':
    try:
        main()
    finally:
        wikipedia.stopme()
